#include <iostream>
#include <boost/asio.hpp>
#include <boost/crc.hpp>
#include <thread>
#include <chrono>

using namespace std;
using namespace boost::asio;

// CRC 计算函数
uint16_t cal_crc(const std::string& data) {
    boost::crc_16_type crc;
    crc.process_bytes(data.data(), data.size());
    return crc.checksum();
}

void send_data(serial_port& p) {
    while (true) { // 构建数据包
        std::string data = "hello";
        uint16_t crc = cal_crc(data);
        std::string packet = "\x02" + std::string(1, static_cast<char>(data.size())) + data + std::string(reinterpret_cast<char*>(&crc), 2);
        boost::asio::write(p, boost::asio::buffer(packet));
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

int main() {
    io_service io;
    try {
        serial_port p(io, "/dev/ttyUSB0"); // 打开串口
        p.set_option(serial_port_base::baud_rate(9600)); // 波特率
        send_data(p);
    } catch (boost::system::system_error& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}
